package edu.hebtu.controller;

import edu.hebtu.mapper.impl.AdminMapper;
import edu.hebtu.mapper.impl.ScoreMapper;
import edu.hebtu.mapper.impl.SubjectMapper;
import edu.hebtu.mapper.impl.UserMapper;
import edu.hebtu.pojo.Score;
import edu.hebtu.pojo.Subject;
import edu.hebtu.pojo.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;

@Controller
public class ScoreController {

    private final ScoreMapper scoreMapper;
    private final UserMapper userMapper;
    private final SubjectMapper subjectMapper;
    private final AdminMapper adminMapper;

    @Autowired
    public ScoreController(ScoreMapper scoreMapper, UserMapper userMapper, SubjectMapper subjectMapper, AdminMapper adminMapper) {
        this.scoreMapper = scoreMapper;
        this.userMapper = userMapper;
        this.subjectMapper = subjectMapper;
        this.adminMapper = adminMapper;
    }

    @RequestMapping("/score_info")
    public String score_info(Model model) {
        List<Score> scores = scoreMapper.findById(null);
        for (Score score : scores) {
            User user = userMapper.findById(score.getUserId()).get(0);          //获取学员信息
            Subject subject = subjectMapper.findById(score.getSubjectId()).get(0);      //获取科目信息
            score.setUserId(user.getName() + "(" + user.getUserId() + ")");
            if (score.getScore() < subject.getPassLine()) {
                score.setSubjectId(subject.getSubjectName() + "(不及格)");
            } else {
                score.setSubjectId(subject.getSubjectName() + "(通过)");
            }
            if ("appear".equals(score.getState())) score.setState("正常");
            if ("make-up".equals(score.getState())) score.setState("补考");
            score.setCreator(adminMapper.findById(score.getCreator()).get(0).getName());
        }
        model.addAttribute("scores", scores);
        return "tables/table-score";
    }

    @RequestMapping("score_add/{userId}")
    public String score_add(@PathVariable("userId") String userId, Model model) {
        List<User> users = userMapper.findById(null);
        users.removeIf(aValue -> aValue.getUserType() == 1 || aValue.getState().equals("licenced"));        //移除教练和已拿证学员信息
        users.sort(Comparator.comparing(User::getName).reversed());
        model.addAttribute("users", users);
        if (userId.equals("null")) userId = users.get(0).getUserId();
        model.addAttribute("userId", userId);
        List<Subject> subjects = subjectMapper.findById(null);
        List<Score> scores = scoreMapper.findById(null);
        String finalUserId = userId;
        scores.removeIf(aValue -> !aValue.getUserId().equals(finalUserId));
        if (scores.size() == 0) {
            if (subjects.size() > 1) {
                subjects.subList(1, subjects.size()).clear();       //只保留科目一，第一次成绩只能是科目一
            }
        } else {
            int f = 0;                          //已通过的科目数
            for (Score score : scores) {
                for (Subject subject : subjects){
                    if (score.getSubjectId().equals(subject.getSubjectId()) && score.getScore() >= subject.getPassLine()) f++;
                }
            }
            if (subjects.size() > 1 && f == 0) {
                subjects.subList(1, subjects.size()).clear();       //只保留科目一，第一次成绩只能是科目一
            } else if (f == subjects.size() - 1) {
                if (subjects.size() > 1) {
                    subjects.subList(0, subjects.size() - 1).clear();       //只保留最后科目，最后一次成绩只能是最后一个科目
                }
            } else {
                subjects.remove(0);                         //中间的科目可以互换
                subjects.remove(subjects.size() - 1);
                for (Score score : scores) {                    //去掉中间的已经通过的科目
                    subjects.removeIf(subject -> score.getSubjectId().equals(subject.getSubjectId()) && score.getScore() >= subject.getPassLine());
                }
            }
        }
        model.addAttribute("subjects", subjects);
        return "add/add-score";
    }

    @RequestMapping("/addScore")
    public String addScore(Score score, Model model) {
        Subject subject = subjectMapper.findById(score.getSubjectId()).get(0);
        if (score.getScore() < 0 || score.getScore() > subject.getScore()) {
            model.addAttribute("msg", subject.getSubjectName() + " 的成绩区间为：0~" + subject.getScore() + "。");
            return score_add(score.getUserId(), model);
        }

        scoreMapper.add(score);

        List<Subject> subjects = subjectMapper.findById(null);
        if (subject.getSubjectId().equals(subjects.get(subjects.size() - 1).getSubjectId())) {
            if (subject.getPassLine() <= score.getScore()) {            //将最后一个科目已通过的学员的状态置为已拿证
                User user = userMapper.findById(score.getUserId()).get(0);
                user.setState("licenced");
                userMapper.update(user);
            }
        }

        return "redirect:/score_info";
    }

    @RequestMapping("/score_delete/{scoreId}")
    public String score_delete(@PathVariable("scoreId") String scoreId, Model model) {
        Score score = scoreMapper.findById(scoreId).get(0);
        score.setUserId(userMapper.findById(score.getUserId()).get(0).getName() + "(" + score.getUserId() + ")");
        Subject subject = subjectMapper.findById(score.getSubjectId()).get(0);      //获取科目信息
        if (score.getScore() < subject.getPassLine()) {
            score.setSubjectId(subject.getSubjectName() + "(不及格)");
        } else {
            score.setSubjectId(subject.getSubjectName() + "(通过)");
        }
        model.addAttribute("score", score);
        return "delete/delete-score";
    }

    @RequestMapping("/deleteScore")
    public String deleteScore(Score score) {
        scoreMapper.delete(score);
        return "redirect:/score_info";
    }

    @RequestMapping("/user_score_info")
    public String user_score_info(Model model, HttpSession session) {
        User user = userMapper.findById(((User) session.getAttribute("user")).getUserId()).get(0);
        List<Score> scores = scoreMapper.findById(null);
        scores.removeIf(aValue -> !aValue.getUserId().equals(user.getUserId()));

        for (Score score : scores) {
            Subject subject = subjectMapper.findById(score.getSubjectId()).get(0);      //获取科目信息
            if (score.getScore() < subject.getPassLine()) {
                score.setSubjectId(subject.getSubjectName() + "(不及格)");
            } else {
                score.setSubjectId(subject.getSubjectName() + "(通过)");
            }
            if ("appear".equals(score.getState())) score.setState("正常");
            if ("make-up".equals(score.getState())) score.setState("补考");
        }

        model.addAttribute("scores", scores);

        return "tables/table-user-score";

    }

}
